<template>
  <div class="flex-container" style="flex-direction: row;">
    <!-- 左侧项目组列表 -->
    <div class="left-group-container">
      <div class="header">
        <span class="title">项目组列表</span>
        <a-button type="primary" icon="plus" @click="handleCreate">
          新增项目组
        </a-button>
      </div>
      <!-- 搜索框 -->
      <div class="search-box">
        <a-input-search
          v-model="searchForm.project_group_name"
          placeholder="请输入项目组名称"
          @search="handleSearch"
          allowClear
          enter-button
        />
      </div>
      <div class="group-list">
        <a-list :data-source="groupList" :loading="groupLoading">
          <a-list-item slot="renderItem" slot-scope="item">
            <a-list-item-meta
              :description="item.remark || '暂无备注'"
              @click="handleSelectGroup(item)"
            >
              <span slot="title" :class="{ active: currentGroup?.project_group_id === item.project_group_id }">
                {{ item.project_group_name }}
              </span>
            </a-list-item-meta>
            <template slot="actions">
              <a-button type="link" @click="handleEdit(item)">编辑</a-button>
              <a-popconfirm
                title="确定要删除该项目组吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(item)"
              >
                <a-button type="link" style="color: #ff4d4f">删除</a-button>
              </a-popconfirm>
            </template>
          </a-list-item>
        </a-list>
      </div>
    </div>

    <!-- 右侧成员列表 -->
    <div class="right-member-container">
      <div class="header">
        <span class="title">{{ currentGroup?.project_group_name || '请选择项目组' }} - 成员列表</span>
        <a-button 
          type="primary" 
          icon="user-add" 
          @click="handleAddMember"
          :disabled="!currentGroup"
        >
          添加成员
        </a-button>
      </div>
      <div class="member-list">
        <a-table
          :columns="columns"
          :data-source="memberList"
          :loading="memberLoading"
          :pagination="false"
          row-key="person_id"
        >
          <template slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确定要移除该成员吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleRemoveMember(record)"
            >
              <a-button type="link" style="color: #ff4d4f">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 新增/编辑项目组弹窗 -->
    <a-modal
      :visible="modalVisible"
      :title="modalType === 'create' ? '新增项目组' : '编辑项目组'"
      :confirmLoading="modalLoading"
      @ok="handleModalSubmit"
      @cancel="handleModalCancel"
    >
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="名称" prop="project_group_name">
          <a-input v-model="form.project_group_name" placeholder="请输入项目组名称" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea v-model="form.remark" placeholder="请输入备注信息" :rows="4" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 添加成员弹窗 -->
    <a-modal
      v-model="memberModalVisible"
      title="添加成员"
      :confirmLoading="memberModalLoading"
      @ok="handleMemberModalSubmit"
      @cancel="handleMemberModalCancel"
    >
      <a-form-model
        ref="memberForm"
        :model="memberForm"
        :rules="memberRules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-model-item label="人员" prop="person_id">
          <a-select
            v-model="memberForm.person_id"
            placeholder="输入姓名搜索"
            :loading="personLoading"
            show-search
            :filter-option="false"
            :default-active-first-option="false"
            :show-arrow="false"
            :not-found-content="personLoading ? '加载中...' : '未找到'"
            @search="handleSearchPerson"
            style="width: 100%"
          >
            <a-select-option
              v-for="item in personList"
              :key="item.person_id"
              :value="item.person_id"
            >
              {{ item.person_name }} ({{ item.department_name }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {
  apiProjectGroupList,
  apiProjectGroupCreate,
  apiProjectGroupUpdate,
  apiProjectGroupDelete,
  apiPersonProjectGroupGetPersons,
  apiPersonProjectGroupAdd,
  apiPersonProjectGroupRemove,
  apiPersonGetAllList
} from '@/api/featch'
import moment from 'moment'

export default {
  name: 'ProjectGroup',
  data() {
    return {
      // 项目组列表
      groupList: [],
      groupLoading: false,
      currentGroup: null,

      // 成员列表
      columns: [
        { title: '姓名', dataIndex: 'person_name' },
        { title: '部门', dataIndex: 'department_name' },
        { title: '角色', dataIndex: 'role' },
        { 
          title: '加入时间', 
          dataIndex: 'join_time',
          customRender: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-'
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      memberList: [],
      memberLoading: false,

      // 项目组表单
      modalVisible: false,
      modalLoading: false,
      modalType: 'create', // create or edit
      form: {
        project_group_id: undefined,
        project_group_name: '',
        remark: ''
      },
      rules: {
        project_group_name: [
          { required: true, message: '请输入项目组名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },

      // 添加成员
      memberModalVisible: false,
      memberModalLoading: false,
      memberForm: {
        person_id: undefined
      },
      memberRules: {
        person_id: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ]
      },
      personList: [],
      personLoading: false,

      // 搜索表单
      searchForm: {
        project_group_name: ''
      }
    }
  },
  mounted() {
    this.getGroupList()
  },
  methods: {
    /**
     * @description 搜索项目组
     */
    handleSearch() {
      this.getGroupList()
    },

    /**
     * @description 获取项目组列表
     */
    async getGroupList() {
      this.groupLoading = true
      try {
        const res = await apiProjectGroupList({
          project_group_name: this.searchForm.project_group_name || undefined
        })
        if (res.code === 200) {
          this.groupList = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.groupLoading = false
    },

    /**
     * @description 选择项目组
     */
    async handleSelectGroup(group) {
      this.currentGroup = group
      await this.getMemberList()
    },

    /**
     * @description 获取成员列表
     */
    async getMemberList() {
      if (!this.currentGroup) return
      
      this.memberLoading = true
      try {
        const res = await apiPersonProjectGroupGetPersons({
          project_group_id: this.currentGroup.project_group_id
        })
        if (res.code === 200) {
          this.memberList = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.memberLoading = false
    },

    /**
     * @description 打开新增弹窗
     */
    handleCreate() {
      this.modalType = 'create'
      this.modalVisible = true
      this.form = {
        project_group_id: undefined,
        project_group_name: '',
        remark: ''
      }
    },

    /**
     * @description 打开编辑弹窗
     */
    handleEdit(group) {
      this.modalType = 'edit'
      this.modalVisible = true
      this.form = {
        project_group_id: group.project_group_id,
        project_group_name: group.project_group_name,
        remark: group.remark
      }
    },

    /**
     * @description 提交表单
     */
    handleModalSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.modalLoading = true
          try {
            const api = this.modalType === 'create' ? apiProjectGroupCreate : apiProjectGroupUpdate
            const res = await api(this.form)
            if (res.code === 200) {
              this.$message.success(this.modalType === 'create' ? '创建成功' : '更新成功')
              this.modalVisible = false
              await this.getGroupList()
              // 如果是编辑当前选中的项目组，需要更新成员列表
              if (this.modalType === 'edit' && this.currentGroup?.project_group_id === this.form.project_group_id) {
                this.currentGroup = res.data
              }
            } else {
              this.$message.error(res.message)
            }
          } catch (err) {
            this.$message.error(err.toString())
          }
          this.modalLoading = false
        }
      })
    },

    /**
     * @description 取消表单
     */
    handleModalCancel() {
      this.modalVisible = false
      this.$refs.form.resetFields()
    },

    /**
     * @description 删除项目组
     */
    async handleDelete(group) {
      this.groupLoading = true
      try {
        const res = await apiProjectGroupDelete({
          project_group_id: group.project_group_id
        })
        if (res.code === 200) {
          this.$message.success('删除成功')
          // 如果删除的是当前选中的项目组，清空选中状态
          if (this.currentGroup?.project_group_id === group.project_group_id) {
            this.currentGroup = null
            this.memberList = []
          }
          await this.getGroupList()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.groupLoading = false
    },

    /**
     * @description 打开添加成员弹窗
     */
    async handleAddMember() {
      this.memberModalVisible = true
      this.memberForm = {
        person_id: undefined
      }
      // 初始加载全部人员
      await this.handleSearchPerson()
    },

    /**
     * @description 搜索人员
     */
    async handleSearchPerson(value) {
      this.personLoading = true
      try {
        const res = await apiPersonGetAllList({
          person_name: value || undefined
        })
        if (res.code === 200) {
          this.personList = res.data
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.personLoading = false
    },

    /**
     * @description 提交添加成员
     */
    handleMemberModalSubmit() {
      this.$refs.memberForm.validate(async valid => {
        if (valid) {
          this.memberModalLoading = true
          try {
            const res = await apiPersonProjectGroupAdd({
              project_group_id: this.currentGroup.project_group_id,
              person_id: this.memberForm.person_id
            })
            if (res.code === 200) {
              this.$message.success('添加成功')
              this.memberModalVisible = false
              await this.getMemberList()
            } else {
              this.$message.error(res.message)
            }
          } catch (err) {
            this.$message.error(err.toString())
          }
          this.memberModalLoading = false
        }
      })
    },

    /**
     * @description 取消添加成员
     */
    handleMemberModalCancel() {
      this.memberModalVisible = false
      this.$refs.memberForm.resetFields()
    },

    /**
     * @description 移除成员
     */
    async handleRemoveMember(member) {
      this.memberLoading = true
      try {
        const res = await apiPersonProjectGroupRemove({
          project_group_id: this.currentGroup.project_group_id,
          person_id: member.person_id
        })
        if (res.code === 200) {
          this.$message.success('移除成功')
          await this.getMemberList()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error(err.toString())
      }
      this.memberLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
.flex-container {
  display: flex;
  height: 100%;
  padding: 24px;
  background: #fff;
  gap: 24px;
}

.left-group-container {
  width: 400px;
  border-right: 1px solid #f0f0f0;
  padding-right: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .search-box {
    margin-bottom: 16px;
  }

  .group-list {
    :deep(.ant-list-item) {
      padding: 12px;
      cursor: pointer;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        background: #f5f5f5;
      }

      .ant-list-item-meta {
        cursor: pointer;
        
        &-title {
          margin-bottom: 4px;
          font-size: 14px;
          
          .active {
            color: #1890ff;
            font-weight: 500;
          }
        }

        &-description {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }
  }
}

.right-member-container {
  flex: 1;
  min-width: 0; // 防止表格溢出

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .member-list {
    :deep(.ant-table-wrapper) {
      .ant-table {
        .ant-table-thead > tr > th {
          background: #fafafa;
        }
      }
    }
  }
}
</style>
